package com.fin.zw.aiqas.job;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobTypeConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.fin.zw.aiqas.entity.QTaskInfo;
import com.fin.zw.aiqas.entity.TaskInfo;
import com.fin.zw.aiqas.enums.Status;
import com.fin.zw.aiqas.enums.TaskTimeType;
import com.fin.zw.aiqas.enums.TaskType;
import com.fin.zw.aiqas.repository.TaskInfoRepository;
import com.fin.zw.aiqas.util.BadRequestException;
import com.querydsl.core.BooleanBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Optional;


/**
 * @Description: 定时任务管理类
 * @Author: ZhangGQ
 * @Date: 2019/9/3 17:38
 */
@Service("elasticJobManager")
public class ElasticJobManager {

    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    @Autowired
    private TaskInfoRepository taskInfoRepository;

    @Autowired
    private TaskSimpleJob taskSimpleJob;




    /**
     * 增加定时任务方法
     * @param JobName 任务名称
     * @param cron 表达式
     */
    public void createJob(String JobName, String cron) {
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration.newBuilder(JobName, cron, 1).misfire(true).build();
        JobTypeConfiguration jobTypeConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, taskSimpleJob.getClass().getCanonicalName());
        LiteJobConfiguration build = LiteJobConfiguration.newBuilder(jobTypeConfiguration).overwrite(true).build();
        JobScheduler jobScheduler = new SpringJobScheduler(taskSimpleJob, zookeeperRegistryCenter, build);
        jobScheduler.init();
    }


    /**
     * 针对具体某一个任务进行定时
     *
     * @param taskId
     */
    public void initJob(Long taskId) {
        Optional<TaskInfo> optional = taskInfoRepository.findById(taskId);
        if (!optional.isPresent()) {
            throw new BadRequestException("", "选择的任务信息不存在！");
        }
        TaskInfo taskInfo = optional.get();
        if (taskInfo.getTaskType().equals(TaskType.AUTOMATIC)
                && taskInfo.getStatus().equals(Status.START)) { //定时任务并且是启动的状态
            String cron = getCron(taskInfo.getCheckTimeType(), taskInfo.getTaskCron());
            createJob("taskInfo_" + taskInfo.getId(), cron);
        }
    }


    public String getCron(TaskTimeType checkTimeType, String taskCron) {
        String result = new String();
        if (checkTimeType.equals(TaskTimeType.EVERYDAY)) { //每天
            String[] mgs = taskCron.split(":");
            if (mgs.length == 3) {
                result = mgs[2] + " " + mgs[1] + " " + mgs[0] + " * * ?";
            }
        } else if (checkTimeType.equals(TaskTimeType.EVERYWEEK)) { //每周
            result = "0 0 0 * * " + taskCron + " ?";
        }
        return result;
    }


    /**
     * 针对所有的定时任务进行定时
     */
    public void initJob() {
        BooleanBuilder builder = new BooleanBuilder();
        QTaskInfo qTaskInfo = QTaskInfo.taskInfo;
        builder.and(qTaskInfo.status.eq(Status.START));
        builder.and(qTaskInfo.taskType.eq(TaskType.AUTOMATIC));
        Iterator<TaskInfo> iterator = taskInfoRepository.findAll(builder).iterator();
        while (iterator.hasNext()) {
            TaskInfo taskInfo = iterator.next();
            String cron = getCron(taskInfo.getCheckTimeType(), taskInfo.getTaskCron());
            createJob("taskInfo_" + taskInfo.getId(), cron);
        }

    }
}
